package com.boot.web.util;

import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;

import java.util.Map;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description HTTP 请求工具 {@link HttpRequestUtil} 请求方法的参数
 * @date 2020/2/24 21:17
 **/
public class Request<S> {

    @Getter
    private String url;
    @Setter
    @Getter
    private HttpMethod method;
    @Setter
    @Getter
    private HttpEntity<S> entity;
    @Setter
    @Getter
    private Map<String, ?> params;

    public Request() {
        url = "http://localhost:8080";
        method = HttpMethod.GET;
    }

    public Request<S> appendUrl(String path) {
        url += path;
        return this;
    }

    public Request<S> setUrl(String url) {
        this.url = url;
        return this;
    }

    public Request<S> setUrl(String url, Object... args) {
        this.url = String.format(url, args);
        return this;
    }

    public Request<S> setUrl(String url, Map<String, Object> map) {
        StringBuilder builder = new StringBuilder(url + '?');
        map.forEach((k, v) -> builder.append(k).append('=').append(v).append('&'));
        builder.setLength(builder.length() - 1);
        this.url = builder.toString();
        return this;
    }

    public Request<S> setUrlTemplate(String url, String... args) {
        StringBuilder builder = new StringBuilder(url + '?');
        for (String arg : args) {
            builder.append(arg).append('=').append('{').append(arg).append('}').append('&');
        }
        builder.setLength(builder.length() - 1);
        this.url = builder.toString();
        return this;
    }

}
